package com.ruoyi.notify.service.impl;

import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import com.rabbitmq.client.Channel;
import com.ruoyi.common.core.domain.NotifyLogVo;
import com.ruoyi.common.rabbitmq.constant.RabbitmqConstants;
import com.ruoyi.common.rabbitmq.domain.WxNotifyTemplate;
import com.ruoyi.common.wx.config.WxMaConfiguration;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@Service
public class WxNotifyServiceImpl {

//    @Autowired
//    RemoteNotifyLogService remoteNotifyLogService;

    @RabbitListener(queues = {RabbitmqConstants.WECHAT_NOTIFY_QUEUE})
    @RabbitHandler
    public void WxSendBatch(WxNotifyTemplate wxNotifyTemplate, Message message, Channel channel) throws IOException {

        channel.basicAck(message.getMessageProperties().getDeliveryTag(),true);

        LinkedList<WxMaSubscribeMessage.MsgData> list = new LinkedList<>();

        Map<String, String> contentMap = wxNotifyTemplate.getContentMap();

        StringBuilder content = new StringBuilder();
        for(String key:contentMap.keySet()){
            WxMaSubscribeMessage.MsgData msgData = new WxMaSubscribeMessage.MsgData(key, contentMap.get(key));
            content.append(contentMap.get(key));
            list.add(msgData);
        }

       String msg = null;
  //    boolean isAck = true;
        try {
           for(String oppenId : wxNotifyTemplate.getToUsers()){
               WxMaConfiguration.getMaService().getMsgService().sendSubscribeMsg(WxMaSubscribeMessage.builder()
                       .templateId(wxNotifyTemplate.getTemlateId())
                       .data(list)
                       .toUser(oppenId)
                       .miniprogramState(wxNotifyTemplate.getMiniprogramState())
                       .page(wxNotifyTemplate.getPage())
                       .build());

           }
        } catch(WxErrorException w) {
            msg = w.getError().getErrorMsg().substring(0,200);
        }catch (Exception e) {
            msg = "网络错误或者未知原因！";
          //  isAck = false;
        }finally {
            int flag = 1;
            if(msg != null){
                flag = 0;
            }


            List<NotifyLogVo> vos = new LinkedList<>();
            List<Long> notifyUserIds = wxNotifyTemplate.getNotifyUserId();
            List<String> notifyUserNames = wxNotifyTemplate.getNotifyUserName();

            for(int i = 0;i < notifyUserIds.size(); i++){
                NotifyLogVo vo = new NotifyLogVo();

                vo.setNotifyTime(System.currentTimeMillis());
                vo.setNotifyUserId(notifyUserIds.get(i));
                vo.setNotifyUserName(notifyUserNames.get(i));
                vo.setNotifyType(1);
                vo.setRemark(msg);
                vo.setNotifyStatus(flag);
                vo.setContent(content.toString());
                vos.add(vo);
            }


//            if(isAck){
//                channel.basicAck(message.getMessageProperties().getDeliveryTag(),true);
//            }
            try{
            //
                //    remoteNotifyLogService.addNotify(vos);
            }catch (Exception e){
                e.printStackTrace();
            }
        }

    }
}
